﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace WpfApplication4
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        BackgroundWorker bw = new BackgroundWorker();

        public MainWindow()
        {

            InitializeComponent();

            bw.WorkerReportsProgress = true;
            bw.DoWork += new DoWorkEventHandler(DoWork);
            bw.ProgressChanged += new ProgressChangedEventHandler(ProgressChanged);
            bw.RunWorkerCompleted += new RunWorkerCompletedEventHandler(Completed);
        }

        //private void buttonStart_Click(object sender, RoutedEventArgs e)
        //{
        //    bw.RunWorkerAsync();
        //}
        

        private async void buttonStart_Click(object sender, RoutedEventArgs e)
        {
            this.tbProgress.Text = "Working...";

            Progress<int> progress = new Progress<int>(percent =>
            {
                tbProgress.Text = percent + "%";
            });

            //bw.RunWorkerAsync();
            await Task.Run(() => DoWork2(progress));

            this.tbProgress.Text = "Done";
        }

        private void DoWork2(IProgress<int> progress)
        {

            for (int i = 1; i <= 10; i++)
            {
                System.Threading.Thread.Sleep(1000);

                progress.Report(i * 10);

            }
        }

        private void DoWork(object sender, DoWorkEventArgs e)
        {
            BackgroundWorker worker = sender as BackgroundWorker;

            for (int i=1; i<= 10; i++)
            {
                System.Threading.Thread.Sleep(5000);
                worker.ReportProgress(i * 10);                
            }
        }

        public void ProgressChanged(object sender, ProgressChangedEventArgs e)
        {
            this.tbProgress.Text = e.ProgressPercentage.ToString();
        }

        public void Completed(object sender, RunWorkerCompletedEventArgs e)
        {
            this.tbProgress.Text = "Done";
        }

    }
}
